package com.ruoyi.common.security.feign;

import cn.hutool.core.util.ReflectUtil;
import feign.QueryMapEncoder;
import feign.codec.EncodeException;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述:
 *
 * @author 31592
 * @date 2023-04-07 23:48
 */
public class InheritedFieldQueryMapEncoder implements QueryMapEncoder {
    @Override
    public Map<String, Object> encode(Object object) throws EncodeException {
        Map<String, Object> fieldNameToValue = new HashMap<>(10);
        if(object == null) return fieldNameToValue;
        Class<?> cls = object.getClass();
        // 这里的ReflectUtil使用的是cn.hutool.core.util.ReflectUtil，会循环查找所有层级父类的字段
        Field[] fields = ReflectUtil.getFields(cls);
        for (Field field : fields) {
            Object value = ReflectUtil.getFieldValue(object, field);
            if (value != null && value != object) {
                if(value instanceof Map){
                    Map valueMap = (Map)value;
                    valueMap.forEach((k,v) -> {
                        fieldNameToValue.put(field.getName() + "['" + k + "']",v);
                    });
                    System.out.println(value);
                }else
                    fieldNameToValue.put(field.getName(), value);
            }
        }
        return fieldNameToValue;
    }
}
